﻿#!/usr/bin/env python3
import os
import requests
from datetime import datetime, timedelta
import time



# 本地目录路径
local_dir = '/backup/'

# WebDAV服务器的URL、用户名和密码
webdav_url = 'http://10.10.10.142:8099'
webdav_user = 'admin'
webdav_password = 'xtlib@Lib2025'

# WebDAV目标目录路径
webdav_target_dir = '/webdav/'

# 创建一个自定义的 requests 会话，禁用 SSL 校验
session = requests.Session()
session.verify = False  # 禁用 SSL 校验

# 定义最大文件年龄（2天）
max_age_in_days = 2
max_age_in_seconds = max_age_in_days * 24 * 60 * 60  # 转换为秒

# 处理重复文件的策略：'overwrite'（覆盖）, 'rename'（重命名），'skip'（跳过）
#handle_duplicate = 'overwrite'  # 选择覆盖（'overwrite'）、重命名（'rename'）或跳过（'skip'）

# 遍历本地目录并上传文件
def upload_files(local_dir, webdav_target_dir):
    # 遍历本地目录中的所有文件
    for filename in os.listdir(local_dir):
        local_file = os.path.join(local_dir, filename)
        if os.path.isfile(local_file):
            webdav_file_path = os.path.join(webdav_target_dir, filename)

            # 上传文件的实际操作
            upload_file(local_file, webdav_file_path)

def upload_file(local_file, webdav_file_path):
    url = webdav_url + webdav_file_path
    try:
        # 获取本地文件的最后修改时间
        local_mod_time = os.path.getmtime(local_file)
        local_mod_datetime = datetime.fromtimestamp(local_mod_time)
        current_time = datetime.now()

        # 计算文件的年龄
        file_age = current_time - local_mod_datetime
        if file_age.days > max_age_in_days:
            print(f"Skipping upload of {webdav_file_path} (File is older than {max_age_in_days} days)")
            return  # 文件超过 2 天，跳过上传

        # 构建 WebDAV 上文件的 URL
        dav_file_url = url

        # 使用 HEAD 请求来检查文件是否存在
        response = session.head(dav_file_url, auth=(webdav_user, webdav_password))

        if response.status_code == 200:
            # 验证文件大小是否一致，这是检查重复的标准
            existing_size = response.headers.get('content-length')
            current_size = os.path.getsize(local_file)

            # 如果文件大小相同，检查文件是否超过 2 天
            if existing_size == current_size:
                print(f"Overwriting {webdav_file_path} (File exists and is within 2 days, will be overwritten)")
                with open(local_file, 'rb') as file:
                    response = session.put(dav_file_url, data=file, auth=(webdav_user, webdav_password))
                    if response.status_code == 201:
                        print(f"Successfully uploaded {local_file} to {webdav_file_path}")
                    else:
                        print(f"Failed to upload {local_file}. Status Code: {response.status_code}")
            else:
                print(f"Uploading {local_file} to {webdav_file_path} (Size mismatch, uploading new version)")
                # 如果文件大小不同，上传新版本
                with open(local_file, 'rb') as file:
                    response = session.put(dav_file_url, data=file, auth=(webdav_user, webdav_password))
                    if response.status_code == 201:
                        print(f"Successfully uploaded {local_file} to {webdav_file_path}")
                    else:
                        print(f"Failed to upload {local_file}. Status Code: {response.status_code}")
        else:
            # 如果 WebDAV 上没有文件，则上传
            print(f"No existing file found at {webdav_file_path}, uploading new file.")
            with open(local_file, 'rb') as file:
                response = session.put(dav_file_url, data=file, auth=(webdav_user, webdav_password))
                if response.status_code == 201:
                    print(f"Successfully uploaded {local_file} to {webdav_file_path}")
                else:
                    print(f"Failed to upload {local_file}. Status Code: {response.status_code}")
    except Exception as e:
        print(f"Failed to upload {local_file}: {e}")


#def upload_directory(local_dir, webdav_target_dir):
#    # 遍历目录中的所有文件
#    for root, dirs, files in os.walk(local_dir):
#        for file in files:
#            local_file = os.path.join(root, file)
#            # 生成WebDAV上的目标路径
#            relative_path = os.path.relpath(local_file, local_dir)
#            upload_file(local_file, relative_path)

# 上传整个目录
#upload_directory(local_dir, webdav_target_dir)
# 调用上传所有文件函数
upload_files(local_dir, webdav_target_dir)